<?php
include_once "IDbDriver.php";
class MySqliDriver extends Base implements IDbDriver
{
    private $_db = null;
    private $_query = null;
    private $_sql = null;

    public function __construct()
    {
        Logger::debug("%s,%s,%s,%s,%s",C('db=>host'), C('db=>user'), C('db=>pwd'), C('db=>dbname'), C('db=>port'));
        $this->_db = new mysqli(C('db=>host'), C('db=>user'), C('db=>pwd'), C('db=>dbname'), C('db=>port'));
        if($this->_db->connect_error) {
            throw new BaseException('[Error] can not connect to the database server by mysql drive,the error is : '.$this->_db->connect_errno);
            return ;
        }

        $this->_db->query('set names "UTF8";');

        if($this->_db->server_version >'5.0.1'){
            $this->_db->query("SET sql_mode=''");
        }

    }

    public function close()
    {
        if (null !== $this->_db) {
            $this->_db->close();
        }
    }

    /**
     * 释放查询
     * @access protected
     * @param void
     * @return void
     */
    protected function _free() {
        mysqli_free_result($this->_query);
        $this->_query = null;
    }

    public function prepare($sql)
    {
        Logger::log("[Info] sql  : " . $sql);
        if (null !== $this->_sql) {
            $this->_sql = null;
        }
        $this->_sql = $sql;
    }

    public function execute()
    {
        if (null === $this->_db) {
            $this->connect();
        }

        if(null !== $this->_query) {
            $this->_free();
        }
		
        $this->_query = $this->_db->query($this->_sql);
        if(!$this->_query) {
            Logger::error("执行了execute()函数,SQL为:".$this->_sql.",错误代码为:".$this->_db->errno.",错误信息为:".$this->_db->error);
        }

        return $this->_query;
    }

    public function getAllByAssocArray()
    {
        $tmpLen = 0;
        $this->_queryResult = array();
        while($arr = mysqli_fetch_array($this->_query,MYSQL_ASSOC)) {
            $this->_queryResult[] = $arr;
            $tmpLen ++;
        }
        $this->_queryNum = $tmpLen;

        return $this->_queryResult;
    }

    /**
     * 开始事务
     */
    public function beginTrans()
    {
        $this->_db->autocommit(false);
    }

    public function commit()
    {
        $this->_db->autocommit(true);
    }

    public function rollback()
    {
        $this->_db->rollback();
    }

    /**
     * Version number query string
     *
     * @access	public
     * @return	string
     */
    public function version(){
        return $this->_db->server_version;
    }

}